package cn.interestingshop.servlet.client;

import cn.interestingshop.entity.Classify;
import cn.interestingshop.entity.Goods;
import cn.interestingshop.service.ClassifyService;
import cn.interestingshop.service.GoodsService;
import cn.interestingshop.service.impl.ClassifyServiceImpl;
import cn.interestingshop.service.impl.GoodsServiceImpl;
import cn.interestingshop.vo.ClassifyVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //2.获取请求参数
        //3.调用service进行业务处理
        ClassifyService service=new ClassifyServiceImpl();
        GoodsService goodsService=new GoodsServiceImpl();
        List<ClassifyVo> list=new ArrayList<>();
        //首先查询一级分类
        List<Classify> classifies = service.selectAll(0);
        for (Classify classify : classifies) {
            ClassifyVo classifyVo=new ClassifyVo();
            classifyVo.setId(classify.getId());
            classifyVo.setClassifyName(classify.getClassifyName());

            //根据一级查询二级分类
            List<Classify> classifies2 = service.selectAll(classify.getId());
            for (Classify classify2 : classifies2) {
                ClassifyVo classifyVo2=new ClassifyVo();
                classifyVo2.setId(classify2.getId());
                classifyVo2.setClassifyName(classify2.getClassifyName());
                //将二级分类放入一级分类的集合中
                classifyVo.getClassifyVos().add(classifyVo2);

                //根据二级分类查询三级分类
                List<Classify> classifies3 = service.selectAll(classify2.getId());
                for (Classify classify3 : classifies3) {
                    ClassifyVo classifyVo3=new ClassifyVo();
                    classifyVo3.setId(classify3.getId());
                    classifyVo3.setClassifyName(classify3.getClassifyName());
                    //将三级分类放入二级分类的集合中
                    classifyVo2.getClassifyVos().add(classifyVo3);
                }
            }
            //查询该分类下面的商品
            List<Goods> goodsList = goodsService.selectAll(classify.getId(), 1, 6);
            classifyVo.setGoodsList(goodsList);

            list.add(classifyVo);
        }
        //4.分析返回结果
        request.setAttribute("list",list);
        request.getRequestDispatcher("Index.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
